<template>
  <div class="print-template-designer">
    <div class="designer-container">
      <!-- 左侧预览区 -->
      <div class="preview-panel">
        <div class="preview-header">打印模板预览区</div>
        <div class="preview-content" ref="previewContent">
          <div class="template-preview" :style="previewStyle">
            <!-- 模板内容 -->
            <div 
              v-for="(component, index) in addedComponents" 
              :key="index"
              class="template-component"
              :style="getComponentStyle(component)"
              @click="selectComponent(component)"
              @dblclick="editTextComponent(component)"
              draggable
              @dragstart="handleDragStart($event, index)"
              @dragend="handleDragEnd"
              @dragover.prevent
              @dragenter.prevent
              @drop="handleDrop($event, index)"
            >
              <template v-if="component.type === 'text'">
                {{ component.value }}
              </template>
              <template v-else-if="component.type === 'table'">
                <table class="preview-table" border="1">
                  <tr>
                    <th v-for="(col, colIndex) in component.columns" :key="colIndex">
                      {{ col.label }}
                    </th>
                  </tr>
                  <tr>
                    <td v-for="(col, colIndex) in component.columns" :key="colIndex">
                      ({{ col.prop }})
                    </td>
                  </tr>
                </table>
              </template>
              <template v-else-if="component.type === 'barcode'">
                <div class="barcode-placeholder">
                  [条码: {{ component.value }}]
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧设置面板 -->
      <div class="settings-panel">
        <!-- 页面参数 -->
        <div class="settings-section">
          <div class="section-title">页面参数</div>
          <div class="form-item">
            <label>背景颜色</label>
            <el-color-picker v-model="templateSettings.backgroundColor" size="small"></el-color-picker>
          </div>
          <div class="form-item">
            <label>模板名称</label>
            <el-input v-model="templateSettings.name" size="small"></el-input>
          </div>
          <div class="form-item">
            <label>模板宽度</label>
            <el-input-number v-model="templateSettings.width" :min="100" :max="2000" size="small"></el-input-number>
          </div>
          <div class="form-item">
            <label>模板高度</label>
            <el-input-number v-model="templateSettings.height" :min="100" :max="2000" size="small"></el-input-number>
          </div>
          <div class="form-item">
            <label>纸张宽度</label>
            <el-input-number v-model="templateSettings.paperWidth" :min="50" :max="500" size="small"></el-input-number>
            <span class="unit">(mm)</span>
          </div>
          <div class="form-item">
            <label>纸张高度</label>
            <el-input-number v-model="templateSettings.paperHeight" :min="50" :max="500" size="small"></el-input-number>
            <span class="unit">(mm)</span>
          </div>
        </div>

        <!-- 样式设置 -->
        <div class="settings-section" v-if="selectedComponent">
          <div class="section-title">样式</div>
          <div class="form-item">
            <label>宽度</label>
            <el-input-number v-model="selectedComponent.styles.width" :min="0" :max="1000" size="small"></el-input-number>
          </div>
          <div class="form-item">
            <label>高度</label>
            <el-input-number v-model="selectedComponent.styles.height" :min="0" :max="1000" size="small"></el-input-number>
          </div>
          <div class="form-item">
            <label>横坐标</label>
            <el-input-number v-model="selectedComponent.styles.x" :min="0" :max="1000" size="small"></el-input-number>
          </div>
          <div class="form-item">
            <label>纵坐标</label>
            <el-input-number v-model="selectedComponent.styles.y" :min="0" :max="1000" size="small"></el-input-number>
          </div>
          <div class="form-item">
            <label>字号</label>
            <el-input-number v-model="selectedComponent.styles.fontSize" :min="8" :max="72" size="small"></el-input-number>
          </div>
          <div class="form-item">
            <label>加粗</label>
            <el-checkbox v-model="selectedComponent.styles.fontWeight"></el-checkbox>
          </div>
          <div class="form-item">
            <label>字体颜色</label>
            <el-color-picker v-model="selectedComponent.styles.fontColor" size="small"></el-color-picker>
          </div>
          <div class="form-item">
            <label>边框颜色</label>
            <el-color-picker v-model="selectedComponent.styles.borderColor" size="small"></el-color-picker>
          </div>
          <div class="form-item">
            <label>对齐方式</label>
            <el-radio-group v-model="selectedComponent.styles.textAlign" size="small">
              <el-radio-button label="left">左对齐</el-radio-button>
              <el-radio-button label="center">居中</el-radio-button>
              <el-radio-button label="right">右对齐</el-radio-button>
            </el-radio-group>
          </div>
          <!-- 条码特有设置 -->
          <template v-if="selectedComponent.type === 'barcode'">
            <div class="form-item">
              <label>条码类型</label>
              <el-select v-model="selectedComponent.styles.barcodeType" size="small">
                <el-option label="Code128" value="Code128"></el-option>
                <el-option label="Code39" value="Code39"></el-option>
                <el-option label="EAN13" value="EAN13"></el-option>
              </el-select>
            </div>
            <div class="form-item">
              <label>高度自动</label>
              <el-checkbox v-model="selectedComponent.styles.autoHeight"></el-checkbox>
            </div>
          </template>
        </div>

        <!-- 组件列表 -->
        <div class="settings-section">
          <div class="section-title">组件</div>
          <div class="component-grid">
            <div 
              v-for="(component, index) in availableComponents" 
              :key="index"
              class="component-item"
              @click="handleAddComponent(component)"
            >
              {{ component.label }}
            </div>
          </div>
        </div>

        <!-- 数据源设置 -->
        <div class="settings-section" v-if="selectedComponent && selectedComponent.type === 'table'">
          <div class="section-title">数据源</div>
          <div class="form-item">
            <label>数据源</label>
            <el-select v-model="selectedComponent.dataSource" placeholder="请选择数据源" size="small">
              <el-option
                v-for="source in dataSources"
                :key="source.value"
                :label="source.label"
                :value="source.value">
              </el-option>
            </el-select>
          </div>
          <div v-if="selectedComponent.dataSource === 'custom'">
            <div v-for="(column, colIndex) in selectedComponent.columns" :key="colIndex" class="form-item">
              <label>列{{ colIndex + 1 }}绑定</label>
              <el-select v-model="column.prop" placeholder="选择字段" size="small">
                <el-option
                  v-for="field in tableFields"
                  :key="field.value"
                  :label="field.label"
                  :value="field.value">
                </el-option>
              </el-select>
            </div>
          </div>
        </div>

        <!-- 已加组件 -->
        <div class="settings-section">
          <div class="section-title">已加组件</div>
          <draggable 
            v-model="addedComponents" 
            group="components" 
            @start="drag=true" 
            @end="drag=false"
          >
            <div 
              v-for="(component, index) in addedComponents" 
              :key="index"
              class="added-component-item"
              :class="{ 'is-selected': selectedComponent === component }"
              @click="selectComponent(component)"
            >
              {{ component.label }}
              <i class="el-icon-close" @click.stop="removeComponent(index)"></i>
            </div>
          </draggable>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button type="primary" size="small" @click="saveTemplate">保存模板</el-button>
          <el-button size="small" @click="previewPrint">打印预览</el-button>
        </div>
      </div>
    </div>

    <!-- 文本编辑对话框 -->
    <el-dialog
      title="编辑文本"
      :visible.sync="textEditDialogVisible"
      width="30%"
    >
      <el-input
        type="textarea"
        :rows="4"
        placeholder="请输入文本内容"
        v-model="editingText"
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="textEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveTextEdit">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { LodopFuncs } from '../../public/LodopFuncs.js';
import draggable from 'vuedraggable';

export default {
  components: {
    draggable
  },
  data() {
    return {
      LODOP: null,
      selectedComponent: null,
      drag: false,
	  receivedTableData: [],
	  receivedCurrentTable: null,
	  receivedTemplateName: '',
      templateSettings: {
        name: '出库单示例',
        width: 770,
        height: 500,
        paperWidth: 215,
        paperHeight: 140,
        backgroundColor: '#FFFFFF' // 添加背景色设置
      },
      availableComponents: [
        { type: 'text', label: '自定义文本', value: '自定义文本' },
        { type: 'text', label: '公司名称', value: '{{companyName}}' },
        { type: 'text', label: '出库单号', value: '{{orderNo}}' },
        { type: 'barcode', label: '单号条码', value: '{{orderNo}}' },
        { type: 'text', label: '客户/供应商', value: '{{customerName}}' },
        { type: 'text', label: '经办人', value: '{{operator}}' },
        { type: 'text', label: '出库类型', value: '{{outType}}' },
        { type: 'text', label: '出库仓库', value: '{{warehouse}}' },
        { type: 'text', label: '出库时间', value: '{{outTime}}' },
        { type: 'text', label: '制单人', value: '{{creator}}' },
        { type: 'text', label: '制单时间', value: '{{createTime}}' },
        { type: 'text', label: '收货人(销售)', value: '{{receiver}}' },
        { type: 'text', label: '收货电话(销售)', value: '{{receiverPhone}}' },
        { type: 'text', label: '收货地址(销售)', value: '{{receiverAddress}}' },
        { type: 'text', label: '摘要', value: '{{remark}}' },
        { type: 'table', label: '出库商品明细', value: 'productTable' }
      ],
      addedComponents: [
        // 初始化组件...
      ],
      // 文本编辑相关
      textEditDialogVisible: false,
      editingComponent: null,
      editingText: '',
      // 拖拽相关
      dragIndex: null,
      // 数据源相关
      dataSources: [
        { label: '出库商品', value: 'stockOutItems' },
        { label: '自定义', value: 'custom' }
      ],
      tableFields: [
        { label: '产品名称', value: 'productName' },
        { label: 'SKU名称', value: 'skuName' },
        { label: '规格型号', value: 'spec' },
        { label: '数量', value: 'quantity' },
        { label: '单价', value: 'price' },
        { label: '总价', value: 'totalPrice' }
      ]
    };
  },
  computed: {
    previewStyle() {
      return {
        width: `${this.templateSettings.width}px`,
        height: `${this.templateSettings.height}px`,
        backgroundColor: this.templateSettings.backgroundColor // 应用背景色
      };
    }
  },
  mounted() {
    this.initLodop();
	// 从路由参数中获取数据
	if (this.$route.query.tableData) {
	  this.receivedTableData = JSON.parse(this.$route.query.tableData);
	  this.receivedCurrentTable = JSON.parse(this.$route.query.currentTable);
	  this.receivedTemplateName = this.$route.query.templateName;
	  
	  // 初始化模板
	  this.initTemplateWithData();
	}
  },
  methods: {
	  initTemplateWithData() {
	    // 清空现有组件
	    this.addedComponents = [];
	    
	    // 设置模板名称
	    this.templateSettings.name = this.receivedTemplateName;
	    
	    // 添加标题
	    this.addTitleComponent();
	    
	    // 添加表格组件
	    this.addTableComponent();
	    
	    // 添加页脚
	    this.addFooterComponent();
	  },
	  
	  addTableComponent() {
	    // 根据接收到的数据创建表格列
	    const columns = [];
	    
	    // 添加固定列
	    columns.push({ label: '行号', prop: 'index', width: 60 });
	    
	    // 添加数据列
	    if (this.receivedTableData.length > 0) {
	      const firstRow = this.receivedTableData[0];
	      Object.keys(firstRow).forEach(key => {
	        if (key !== 'id') { // 排除id字段
	          columns.push({
	            label: this.getColumnLabel(key),
	            prop: key,
	            width: this.calculateColumnWidth(key, firstRow[key])
	          });
	        }
	      });
	    }
	    
	    const tableComponent = {
	      type: 'table',
	      label: '药品库存数据',
	      value: 'drugInventoryTable',
	      styles: {
	        x: 20,
	        y: 70,
	        width: 700,
	        height: 300,
	        fontSize: 12,
	        fontWeight: false,
	        fontColor: '#000000',
	        borderColor: '#000000',
	        textAlign: 'left'
	      },
	      columns: columns,
	      dataSource: 'custom'
	    };
	    
	    this.addedComponents.push(tableComponent);
	    this.selectComponent(tableComponent);
	  },
	      
	      addTitleComponent() {
	        const titleComponent = {
	          type: 'text',
	          label: '标题',
	          value: this.receivedTemplateName,
	          styles: {
	            x: 50,
	            y: 20,
	            width: 600,
	            height: 30,
	            fontSize: 20,
	            fontWeight: true,
	            fontColor: '#000000',
	            borderColor: 'transparent',
	            textAlign: 'center'
	          }
	        };
	        this.addedComponents.push(titleComponent);
	      },
	    calculateColumnWidth(key, sampleValue) {
	      // 根据内容和标题计算列宽
	      const label = this.getColumnLabel(key);
	      const content = sampleValue ? sampleValue.toString() : '';
	      
	      // 基础宽度
	      let width = 80;
	      
	      // 根据内容长度调整
	      if (content.length > 10) {
	        width = Math.min(200, Math.max(width, content.length * 8));
	      }
	      
	      // 根据标题长度调整
	      if (label.length > 6) {
	        width = Math.max(width, label.length * 10);
	      }
	      
	      // 特殊字段处理
	      if (key === 'drugName') {
	        width = 150; // 药品名称需要更宽
	      } else if (key === 'drugspec') {
	        width = 120; // 规格描述需要更宽
	      }
	      
	      return width;
	    },
	      
	      addFooterComponent() {
	        const footerComponent = {
	          type: 'text',
	          label: '页脚',
	          value: '打印时间: {{currentTime}}',
	          styles: {
	            x: 400,
	            y: 400,
	            width: 300,
	            height: 20,
	            fontSize: 12,
	            fontWeight: false,
	            fontColor: '#666666',
	            borderColor: 'transparent',
	            textAlign: 'right'
	          }
	        };
	        this.addedComponents.push(footerComponent);
	      },
	      
	      getColumnLabel(key) {
	        // 根据key返回对应的中文标签
	        const labelMap = {
	          'drugType': '药品类型',
	          'drugName': '药品名称',
	          'drugUnt': '药品单位',
	          'code': '药品编码',
	          'dosform': '药品剂型',
	          'drugspec': '规格描述',
	          'pacspec': '包装规格',
	          'purcAmt': '成本金额',
	          'purcCnt': '库存数量',
	          'saleAmt': '零售金额',
	          'shedId': '库房序号'
	        };
	        return labelMap[key] || key;
	      },
	      
    initLodop() {
      this.LODOP = getLodop();
      if (!this.LODOP) {
        this.$message.error('未能成功加载Lodop打印插件，请检查是否已安装');
        return false;
      }
      return true;
    },
    getComponentStyle(component) {
      return {
        position: 'absolute',
        left: `${component.styles.x}px`,
        top: `${component.styles.y}px`,
        width: `${component.styles.width}px`,
        height: `${component.styles.height}px`,
        fontSize: `${component.styles.fontSize}px`,
        fontWeight: component.styles.fontWeight ? 'bold' : 'normal',
        color: component.styles.fontColor,
        borderColor: component.styles.borderColor,
        textAlign: component.styles.textAlign
      };
    },
    selectComponent(component) {
      this.selectedComponent = component;
    },
    
    // 编辑文本组件
    editTextComponent(component) {
      if (component.type === 'text') {
        this.editingComponent = component;
        this.editingText = component.value;
        this.textEditDialogVisible = true;
      }
    },
    
    // 保存文本编辑
    saveTextEdit() {
      if (this.editingComponent) {
        this.editingComponent.value = this.editingText;
        this.textEditDialogVisible = false;
        this.$message.success('文本已更新');
      }
    },
    
    handleAddComponent(component) {
      const newComponent = JSON.parse(JSON.stringify(component));
      newComponent.styles = {
        x: 0,
        y: this.addedComponents.length * 30,
        width: 200,
        height: 25,
        fontSize: 12,
        fontWeight: false,
        fontColor: '#000000',
        borderColor: '#000000',
        textAlign: 'left'
      };
      
      if (newComponent.type === 'table') {
        newComponent.columns = [
          { label: '列1', prop: 'col1', width: 100 },
          { label: '列2', prop: 'col2', width: 100 }
        ];
        newComponent.dataSource = 'custom';
      }
      
      this.addedComponents.push(newComponent);
      this.selectComponent(newComponent);
    },
    removeComponent(index) {
      this.addedComponents.splice(index, 1);
      if (this.selectedComponent === this.addedComponents[index]) {
        this.selectedComponent = null;
      }
    },
    saveTemplate() {
      const templateData = {
        settings: this.templateSettings,
        components: this.addedComponents
      };
      
      // 这里可以调用API保存模板或使用localStorage
      localStorage.setItem('printTemplate', JSON.stringify(templateData));
      this.$message.success('模板保存成功');
    },
    previewPrint() {
      if (!this.LODOP) {
        this.$message.error('打印插件未初始化');
        return;
      }
      
      this.LODOP.PRINT_INIT("打印预览");
      this.setupPrintPage();
      this.LODOP.PREVIEW();
    },
    setupPrintPage() {
      let LODOP = getLodop();
      
      // 设置纸张大小
      LODOP.SET_PRINT_PAGESIZE(1, this.templateSettings.paperWidth, this.templateSettings.paperHeight, '');
      
      // 添加打印内容
      this.addedComponents.forEach(comp => {
        if (comp.type === 'text') {
          LODOP.ADD_PRINT_TEXT(
            comp.styles.y, 
            comp.styles.x, 
            comp.styles.width, 
            comp.styles.height, 
            comp.value
          );
          LODOP.SET_PRINT_STYLEA(0, "FontSize", comp.styles.fontSize);
          LODOP.SET_PRINT_STYLEA(0, "Bold", comp.styles.fontWeight ? 1 : 0);
          LODOP.SET_PRINT_STYLEA(0, "Alignment", this.getLodopAlignment(comp.styles.textAlign));
        } else if (comp.type === 'table') {
          // 添加表头
          let yPos = comp.styles.y;
          let xPos = comp.styles.x;
          
          // 添加列标题
          comp.columns.forEach(col => {
            LODOP.ADD_PRINT_TEXT(
              yPos, 
              xPos, 
              col.width, 
              20, 
              col.label
            );
            LODOP.SET_PRINT_STYLEA(0, "FontSize", 12);
            LODOP.SET_PRINT_STYLEA(0, "Bold", 1);
            xPos += col.width;
          });
          
          // 添加表格数据行
          yPos += 25;
          this.receivedTableData.forEach((row, rowIndex) => {
            xPos = comp.styles.x;
            comp.columns.forEach(col => {
              let value = row[col.prop] || '';
              if (col.prop === 'index') {
                value = rowIndex + 1;
              }
              
              LODOP.ADD_PRINT_TEXT(
                yPos, 
                xPos, 
                col.width, 
                20, 
                value
              );
              LODOP.SET_PRINT_STYLEA(0, "FontSize", 10);
              xPos += col.width;
            });
            yPos += 20;
          });
        } else if (comp.type === 'barcode') {
          LODOP.ADD_PRINT_BARCODE(
            comp.styles.y,
            comp.styles.x,
            comp.styles.width,
            comp.styles.height,
            comp.styles.barcodeType || "Code128",
            comp.value
          );
        }
      });
    },
    getLodopAlignment(align) {
      switch(align) {
        case 'left': return 1;
        case 'center': return 2;
        case 'right': return 3;
        default: return 1;
      }
    },
    
    // 拖拽功能实现
    handleDragStart(event, index) {
      this.dragIndex = index;
      event.dataTransfer.setData('text/plain', index);
    },
    
    handleDragEnd() {
      this.dragIndex = null;
    },
    
    handleDrop(event, targetIndex) {
      event.preventDefault();
      
      if (this.dragIndex === null || this.dragIndex === targetIndex) return;
      
      // 移动组件位置
      const movedComponent = this.addedComponents.splice(this.dragIndex, 1)[0];
      this.addedComponents.splice(targetIndex, 0, movedComponent);
      
      // 更新组件坐标
      movedComponent.styles.x = event.offsetX;
      movedComponent.styles.y = event.offsetY;
      
      this.$message.success('组件位置已更新');
    }
  }
};
</script>

<style lang="less" scoped>
	/* 原有样式基础上添加 */
	.template-component {
	  cursor: move;
	  user-select: none;
	  
	  &:hover {
	    box-shadow: 0 0 0 2px #409eff;
	    z-index: 10;
	  }
	}
	
	.template-preview {
	  background-color: v-bind('templateSettings.backgroundColor');
	  transition: background-color 0.3s;
	}
	
	.settings-section {
	  max-height: 888px;
	  overflow-y: auto;
	}
	
	.data-source-setting {
	  margin-top: 15px;
	  padding: 10px;
	  background-color: #f9f9f9;
	  border-radius: 4px;
	}
.print-template-designer {
  height: 100%;
  padding: 20px;
  background-color: #f5f5f5;

  .designer-container {
    display: flex;
    height: calc(100% - 280px);
    background-color: var(--primary-color, #409EFF) !important;
    color: var(--text-color, #304156) !important;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .preview-panel {
    flex: 1;
    padding: 20px;
    border-right: 1px solid #e6e6e6;

    .preview-header {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 20px;
      color: #333;
    }

    .preview-content {
      height: calc(100% - 280px);
      overflow: auto;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #f9f9f9;
      border: 1px dashed #ddd;
    }

    .template-preview {
      background-color: #fff;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
      position: relative;
      overflow: hidden;
    }

    .template-component {
      position: absolute;
      padding: 5px;
      box-sizing: border-box;
      overflow: hidden;
      cursor: pointer;
      
      &:hover {
        box-shadow: 0 0 0 2px #409eff;
      }
      
      &.selected {
        box-shadow: 0 0 0 2px #67c23a;
      }
    }

    .preview-table {
      width: 100%;
      height: 100%;
      border-collapse: collapse;

      th, td {
        border: 1px solid #ddd;
        padding: 6px;
        text-align: center;
      }

      th {
        background-color: #f5f5f5;
      }
    }

    .barcode-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #f5f5f5;
      color: #666;
      font-family: monospace;
    }
  }

  .settings-panel {
    width: 360px;
    padding: 12px;
    overflow-y: auto;

    .settings-section {
      margin-bottom: 12px;
      border-bottom: 1px solid #eee;
      padding-bottom: 12px;

      &:last-child {
        border-bottom: none;
      }
    }

    .section-title {
      font-size: 14px;
      font-weight: bold;
      margin-bottom: 15px;
      color: #333;
    }

    .form-item {
      display: flex;
      align-items: center;
      margin-bottom: 6px;

      label {
        width: 80px;
        font-size: 12px;
        color: #666;
      }

      .el-input,
      .el-input-number,
      .el-select {
        flex: 1;
      }

      .unit {
        margin-left: 10px;
        font-size: 12px;
        color: #999;
      }
    }

    .component-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 10px;
    }

    .component-item {
      padding: 8px;
      background-color: #f5f7fa;
      border-radius: 4px;
      cursor: pointer;
      text-align: center;
      font-size: 12px;

      &:hover {
        background-color: #ebeff5;
        color: #409eff;
      }
    }

    .added-component-item {
      padding: 8px 15px;
      margin-bottom: 8px;
      background-color: #f5f7fa;
      border-radius: 4px;
      cursor: move;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 12px;

      &:hover {
        background-color: #ebeff5;
      }

      &.is-selected {
        background-color: #ecf5ff;
        border-left: 3px solid #409eff;
      }

      .el-icon-close {
        color: #f56c6c;
        cursor: pointer;

        &:hover {
          color: darken(#f56c6c, 10%);
        }
      }
    }

    .action-buttons {
      margin-top: 20px;
      text-align: right;

      .el-button {
        margin-left: 10px;
      }
    }
  }
}
</style>